import { ref, reactive, createVNode } from "vue";
// 导入提示方法
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
// 导入注册接口
import { registerUser } from "@/api/userAPI";

export const useAddUser = (getUserData) => {
  // 添加用户框显示状态
  const addVisible = ref(false);

  // 点击添加用户显示添加用户框
  const handleShowAddModal = () => {
    addVisible.value = true;
  };

  // 表单内容
  const addModel = reactive({
    username: "",
    password: "",
    email: "",
    mobile: "",
    role_id: "3",
  });

  // 表单ref
  const addFormRef = ref(null);

  // 关闭模态框
  const addCloselModal = () => {
    addFormRef.value.resetFields();
  };

  // 点击确认
  const handleAddOk = () => {
    addFormRef.value
      .validate()
      .then((res) => {
        // 二次确认
        Modal.confirm({
          title: "确认提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "您是否确认添加用户",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            const { username, password, email, mobile, role_id } = res;
            // 参数
            const params = {
              username,
              password,
              email,
              mobile,
              role_id: parseInt(role_id),
            };
            // 发送注册用户请求
            registerUser(params)
              .then((res) => {
                if (res.status === 205) {
                  return message.info(res.msg);
                }
                if (res.status === 200) {
                  message.success(res.msg);
                  addVisible.value = false;
                  // 重新获取数据渲染
                  getUserData();
                }
              })
              .catch((error) => {
                throw new Error(error);
              });
          },
          onCancel() {
            message.info("已取消");
          },
        });
      })
      .catch((error) => {
        throw new Error(error);
      });
  };

  return {
    addVisible,
    handleShowAddModal,
    addModel,
    addFormRef,
    addCloselModal,
    handleAddOk,
  };
};
